package com.sca.order.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sca.order.constant.RedisKeyConstant;
import com.sca.order.entity.Good;
import com.sca.order.entity.Stock;
import com.sca.order.service.GoodService;
import com.sca.order.service.StockService;
import com.sca.order.utils.GoodBloomFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liuxianfei
 * @since 2020/11/3 13:19
 */
@Slf4j
@Component
public class Runner implements ApplicationRunner {

    private final GoodService goodService;
    private final StockService stockService;
    private final RedisTemplate<String, Object> redisTemplate;

    public Runner(GoodService goodService, StockService stockService, RedisTemplate<String, Object> redisTemplate) {
        this.goodService = goodService;
        this.stockService = stockService;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void run(ApplicationArguments args) {
        List<Good> list = goodService.list();
        if (!list.isEmpty()) {
            List<Long> ids = list.stream().map(Good::getId).collect(Collectors.toList());
            GoodBloomFilter.init(ids);
        }
        Stock one = stockService.getOne(new LambdaQueryWrapper<Stock>().eq(Stock::getGoodId, 1));
        if (one != null) {
            redisTemplate.opsForValue().set(RedisKeyConstant.ORDER_STR_SECKILL + 1, one.getNum());
            log.info("good stock is init for redis success.");
        }
        // 清理库存锁
        redisTemplate.delete(RedisKeyConstant.STOCK_STR_LOCK);
    }

}
